import api from '@/api/index'

const state = {
  siteConfig: {
    siteName: '论坛社区',
    siteDescription: '一个交流讨论的平台',
    logoUrl: '',
    faviconUrl: '',
    footerText: '© 2023 Forum Community',
    registerEnabled: true,
    commentAuditEnabled: false
  },
  isLoading: false
}

const mutations = {
  SET_SITE_CONFIG(state, config) {
    state.siteConfig = config
  },
  SET_LOADING(state, loading) {
    state.isLoading = loading
  }
}

const actions = {
  // 获取站点配置
  fetchSiteConfig({ commit }) {
    commit('SET_LOADING', true)
    return new Promise((resolve, reject) => {
      api.config.getSiteConfig()
        .then(response => {
          if (response.code === 0) {
            commit('SET_SITE_CONFIG', response.data || state.siteConfig)
            resolve(response.data)
          } else {
            reject(response.message || '获取站点配置失败')
          }
        })
        .catch(() => {
          // 如果API失败，保持原有默认配置
          resolve(state.siteConfig)
        })
        .finally(() => {
          commit('SET_LOADING', false)
        })
    })
  },
  
  // 更新站点配置（仅限管理员）
  updateSiteConfig({ commit }, config) {
    commit('SET_LOADING', true)
    return new Promise((resolve, reject) => {
      api.config.updateSiteConfig(config)
        .then(response => {
          if (response.code === 0) {
            commit('SET_SITE_CONFIG', config)
            resolve()
          } else {
            reject(response.message || '更新站点配置失败')
          }
        })
        .catch(error => {
          reject(error.message || '更新站点配置失败')
        })
        .finally(() => {
          commit('SET_LOADING', false)
        })
    })
  }
}

const getters = {
  siteConfig: state => state.siteConfig,
  isLoading: state => state.isLoading
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 